package com.yonyou.crm.cum.contact.appctrl;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.yonyou.crm.bpub.list.entity.*;
import com.yonyou.crm.common.base.AppBaseCtrl;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.apputil.AppRequestUtil;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.util.*;
import com.yonyou.crm.common.sort.entity.AppSortPlanEnum;
import com.yonyou.crm.cum.contact.entity.ContactVO;
import com.yonyou.crm.cum.contact.rmitf.IContactRmService;

@RestController
@RequestMapping(value = "/{version}/mcum/contacts")
public class AppContactCtrl extends AppBaseCtrl {

    @Autowired
    private IContactRmService service;
	
    /**
     * 新增与修改
     * @param version
     * @param id
     * @param request
     * @param response
     * @return
     * @throws CrmMessageException
     */
	@RequestMapping(value="/{id}", method = RequestMethod.POST)
	public Object save(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject dataJsonObject = AppRequestUtil.getFormParamObject(request);
		
		ContactVO contact = AppRequestUtil.getVO(dataJsonObject.getJSONObject("header"), ContactVO.class);
		if (contact == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "联系人实体转换失败");
		}
		
		String errorMsg = insertValidator(contact);
		if (!errorMsg.equals("")) {
			throw new CrmMessageException(AppCodeConstant.ServerError, errorMsg);
		}
		
		Map<String, Object> param = new HashMap<String, Object>();
		setBizType(dataJsonObject, param);
		
		if (id.equals(0L)) {
			//relateMap标识是否是新增拜访的任务卡数据
			Map<String, String> relateMap = (Map<String, String>)dataJsonObject.getJSONObject("relateMap");
			if ( relateMap != null) {
				param.put("relateMap", relateMap);
				contact = service.insert(contact, param);
			} else {
				contact = service.insert(contact);
			}
		} else {
			contact.setId(id);
			contact = service.update(contact);
		}
		
		if (contact.getId() == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "获取自增主键失败，未保存成功");
		}
		return ResponseUtil.getObject();
	}
	
	/**
	 * 新增校验
	 * @param contact
	 * @return
	 */
	private String insertValidator(ContactVO contact) {
		String Message = "";
		if (!StringUtils.isNotBlank(contact.getName())) {
			Message = "联系人名称不能为空";
        }
		if (contact.getCustomer() == null || contact.getCustomer() == 0) {
			Message = "联系人客户不能为空";
		}
		/*
		if (contact.getCountry() == 0) {
			Message = "联系人国家不能为空";
		}
		*/
		return Message;
	}
	
	/**
	 * 列表（不分页）
	 * @param version
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="list", method = RequestMethod.GET)
	public Object getNoPageList(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) {
		//JSONObject paramObject = RequestUtil.getParamObject(request);
		Map<String, Object> searchMap = new HashMap<String, Object>();
		// TODO...
		// searchMap = (Map<String, Object>)paramObject.get("condition");
			
		List<AppListVO> list = service.getListForApp(searchMap);
		
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("list", list);
		return ResponseUtil.getObject(map);
	}
	
	/**
	 * 列表（分页）
	 * @param version
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object getList(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		int page = paramObject.getInt("page");
		int pageSize = paramObject.getInt("pageSize");
		checkPageInfo(page, pageSize);
		Page<ContactVO> pageInfo = new Page<ContactVO>(page, pageSize);
		
		Map<String, Object> searchMap = new HashMap<String, Object>();
		getSearchKeyForList(paramObject, searchMap); //搜索关键字
		getFilterForList(paramObject, searchMap); //列表筛选
		getOptionForList(paramObject, searchMap); //列表数据分类
		getSortOrderForPage(paramObject, pageInfo); //排序依据

		Page<ContactVO> pagelist = service.getList(pageInfo, searchMap);
		List<ContactVO> dataList = pagelist.getData();
		List<AppListVO> list = new ArrayList<AppListVO>();
		if (dataList != null) {
			for (int i = 0; i<dataList.size(); i++) {
				ContactVO contact = dataList.get(i);
				AppListVO listVO = tranVoToAppListVO(contact);
				list.add(listVO);
			}
		}
		
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("list", list);
		return ResponseUtil.getObject(map);
	}
	
	/**
	 * 将数据转化为App列表数据
	 * @param contact
	 * @return
	 */
	public AppListVO tranVoToAppListVO(ContactVO contact){
		AppListVO listVO = new AppListVO();
		listVO.setId(contact.getId());
		
		//左右两侧图标
		List<AppListSpecialVO> specialList = new ArrayList<>();
		getAppListSpecialVO(contact, specialList);
		listVO.setSpeciallist(specialList);

		List<List<AppListValueVO>> valueList = new ArrayList<>();
		List<AppListValueVO> colList = new ArrayList<>();
		AppListValueVO listValue = new AppListValueVO();
		
		listValue = new AppListValueVO();
		listValue.setItemkey("name");
		listValue.setDisplayvalue(contact.getName());
		colList.add(listValue);
		
		listValue = new AppListValueVO();
		listValue.setItemkey("position");
		listValue.setDisplayvalue(contact.getPost());
		colList.add(listValue);
		
		valueList.add(colList);
		colList = new ArrayList<>();
		
		listValue = new AppListValueVO();
		listValue.setItemkey("company");
		listValue.setDisplayvalue(contact.getDeptName());
		colList.add(listValue);
		
		valueList.add(colList);
		colList = new ArrayList<>();
		
		listValue = new AppListValueVO();
		listValue.setItemkey("followUp");
		//TODO跟进时间
		listValue.setDisplayvalue("");
		colList.add(listValue);
		
		listVO.setValuelist(valueList);
		return listVO;
	}
	
	/**
	 * 左右两侧图标
	 * @param contact
	 * @param specialList
	 */
	private void getAppListSpecialVO(ContactVO contact, List<AppListSpecialVO> specialList) {
		AppListSpecialVO icon;
		
		icon = new AppListSpecialVO();
		icon.setType("pic");
		icon.setPosition("left");
		icon.setValue(contact.getPhoto());
		specialList.add(icon);
		
		icon = new AppListSpecialVO();
		icon.setType("phone");
		icon.setPosition("right");
		List<String> phoneList = new ArrayList<>();
		getPhoneList(contact, phoneList);
		icon.setValue(phoneList);
		specialList.add(icon);
	}
	
	/**
	 * 获取电话列表
	 * @param contact
	 * @param phoneList
	 */
	private void getPhoneList(ContactVO contact, List<String> phoneList) {
		if ((contact.getMobile() != null) && (!contact.getMobile().equals(""))) {
			phoneList.add(contact.getMobile());
		}
		if ((contact.getOfficePhone() != null) && (!contact.getOfficePhone().equals(""))) {
			phoneList.add(contact.getOfficePhone());
		}
		if ((contact.getHomePhone() != null) && (!contact.getHomePhone().equals(""))) {
			phoneList.add(contact.getHomePhone());
		}
	}

	/**
	 * 排序依据
	 * @param paramObject
	 * @param pageInfo
	 * @throws CrmMessageException
	 */
	private void getSortOrderForPage(JSONObject paramObject, Page<ContactVO> pageInfo) throws CrmMessageException {
		String sortStr = "";
		String orderStr = "";
		Map<String, String> sortInfo = new HashMap<>();
		getSortForList(paramObject, sortInfo);
		if ((sortInfo != null) && (sortInfo.size() > 0)) {
			orderStr = String.valueOf(sortInfo.get("order"));
			Integer sortNum = Integer.valueOf(String.valueOf(sortInfo.get("field")));
			if (sortNum == AppSortPlanEnum.NAME.getValue()) {
				sortStr = "contact.`name`";
			} else if(sortNum == AppSortPlanEnum.CREATETIME.getValue()){
				sortStr = "contact.sys_created_time";
			} else if(sortNum == AppSortPlanEnum.FOLLOWUPTIME.getValue()){
				//TODO跟进时间来自哪个表哪个字段
				sortStr = "contact.follow_time";
			} else {
				sortStr = "convert(contact.name using gbk)";
				orderStr = "asc";
			}
		}
		pageInfo.setSort(sortStr);
		pageInfo.setOrder(orderStr);
	}
	
	/**
	 * 删除
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
		service.delete(id);
		return ResponseUtil.getObject();
	}
	
	/**
	 * 关注
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="/{id}/follow", method = RequestMethod.PUT)
	public Object follow(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObject = RequestUtil.getParamObject(request);
		String followState = paramObject.getString("followState");
		
		if (id == null) {
			throw new CrmMessageException(AppCodeConstant.ClientError, "联系人id不能为空");
		}
		
		if (followState.equals("N")) {
			service.deleteFollow(id);
		} else if (followState.equals("Y")) {
			service.insertFollow(id);
		} else {
			throw new CrmMessageException(AppCodeConstant.ClientError, "非法联系人关注标识");
		}

		return ResponseUtil.getObject();
	}
	
}
